package org.mybatis.generator.plugins;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;

import java.util.Properties;

public class CustomCommentGenerator implements CommentGenerator {

    private boolean addRemarkComments = true;

    @Override
    public void addConfigurationProperties(Properties properties) {
        // 从 generatorConfig.xml 中读取 addRemarkComments 配置
        String remarkComment = properties.getProperty("addRemarkComments");
        if ("true".equalsIgnoreCase(remarkComment)) {
            this.addRemarkComments = true;
        }
    }

    /**
     * 给类添加注释（使用表注释）
     */
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if (addRemarkComments && introspectedTable.getRemarks() != null && !introspectedTable.getRemarks().isEmpty()) {
            topLevelClass.addJavaDocLine("/**");
            topLevelClass.addJavaDocLine(" * " + introspectedTable.getRemarks());
            topLevelClass.addJavaDocLine(" */");
        }
    }

    /**
     * 给字段添加注释（使用字段 comment）
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        //添加字段注释
        if (addRemarkComments && introspectedColumn.getRemarks() != null && !introspectedColumn.getRemarks().isEmpty()) {
            field.addJavaDocLine("/** " + introspectedColumn.getRemarks() + " */");
        }
        // 获取表名和字段名
        String tableName = introspectedTable.getFullyQualifiedTable().getIntrospectedTableName(); // 不带库名
        String columnName = introspectedColumn.getActualColumnName();
//
//        //仅对 user 表的 username 字段加 @NotBlank 注解
//        if ("user".equalsIgnoreCase(tableName) && "username".equalsIgnoreCase(columnName)) {
//            field.addAnnotation("@NotBlank");
//        }
    }

    // 不生成方法注释
    @Override public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {}
    @Override public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {}
    @Override public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {}
    @Override public void addJavaFileComment(CompilationUnit compilationUnit) {}
    @Override public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {}
    @Override public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {}
    @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable) {}
}

